# Create your views here.
from django.template import Template, Context, RequestContext
from django.shortcuts import render_to_response
from django.contrib.auth.models import User
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.contrib import auth
from osmp.users.models import UserProfile, Authority
from osmp.host.models import Product

def user_auth_pids_bak(id,pidlist = []):
    alst = Authority.objects.filter(uid = id)
    for a in alst:
        if not Product.objects.filter(ppid = a.pid.id):
            pidlist.append(a.pid.id)
        else:
            pass
#            user_auth_pids(a.pid.id,pidlist)
    return pidlist


def user_auth_pids(id, pidlist = [], auths=[]):
    if id != -2:
        alst = Authority.objects.filter(uid = id)
        auths = []
        for a in alst:
            auths.append(a.pid)

    print "uid", id
    for a in auths:
        #have no children
        sub = Product.objects.filter(ppid = a.id)
        if not sub and not a.id in pidlist:
            pidlist.append(a.id)
        else:
            user_auth_pids(-2, pidlist, sub)
    return pidlist

def user_auth_pids1(id,pidlist = [], flag=0):
    if flag == 0:
        #uid
        alst = Authority.objects.filter(uid = id)
    else:
        #pid,get sub pid
        alst = Product.objects.filter(ppid = id)
        
    for a in alst:
        if flag == 0:
            pid = a.pid.id
        else:
            pid = a.id
        if not Product.objects.filter(ppid = pid):
            pidlist.append(pid)
        else:
            print pid
            user_auth_pids(pid, pidlist, 1)
    return pidlist




def login(request):
    print request.user
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = auth.authenticate(username=username, password=password)
        if user is not None:
            auth.login(request, user)
            prof = UserProfile.objects.get(user = user )
            request.session['user'] = prof
            auth_pids = []
            user_auth_pids(user.id, auth_pids)
            request.session['auth_pids'] = auth_pids
            return HttpResponseRedirect("/")
        else:
            errors = True
            return render_to_response("login.html",locals())
    else:
        return render_to_response("login.html",locals())

def logout(request):
    auth.logout(request)
    # Redirect to a success page.
    return HttpResponseRedirect("/accounts/login/")
